import {nanoid} from "nanoid";
import {TodosType, TodoType, event} from "../type/toList";
import {ref, watch} from "vue";

export const useFunction = () => {

    const todoList = ref<TodosType>(JSON.parse(localStorage.getItem("todoList") as string) || []);

    watch(todoList.value, () => {
        localStorage.setItem("todoList", JSON.stringify(todoList.value));
    });

    // 添加内容
    const addToList = (e: KeyboardEvent) => {
        todoList.value.push({
            id: nanoid(),
            thing: (e.target as event).value,
            done: false
        });
        (e.target as event).value = ''
    }

    // 修改选中状态
    const alterDone = (id: string) => {
        todoList.value = todoList.value.map((item: TodoType) => {
            item.id === id ? item.done = !item.done : item.done
            return item
        })
    }

    // 删除对应数据
    const deleteItem = (id: string) => {
        todoList.value = todoList.value.filter((item: TodoType) => item.id !== id)
        localStorage.setItem("todoList", JSON.stringify(todoList.value));
    }

    // 全选全不选
    const isCheckedAll = (checked: boolean) => {
        todoList.value = todoList.value.map((item: TodoType) => {
            item.done = checked
            return item
        })
    }

    // 清除已完成数量
    const deleteCheckedAll = () => {
        todoList.value = todoList.value.filter((item: TodoType) => item.done !== true)
        localStorage.setItem("todoList", JSON.stringify(todoList.value));
    }

    return {
        addToList,
        alterDone,
        deleteItem,
        isCheckedAll,
        deleteCheckedAll,
        todoList
    }
}